package com.android.jingweiapp.XMLPhase;

import android.content.Context;
import android.util.Xml;

import com.android.jingweiapp.util.CommonUtil;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by cuiwenrui-pc on 15/11/8.
 */
public class GetJGOfficeXMLPhase implements BaseXMLPhase {
    @Override
    public String phaseResponceXML(InputStream inputStream) {
        try {
            XmlPullParser parser = Xml.newPullParser();
            parser.setInput(inputStream, "UTF-8");
            int eventType = parser.getEventType();// 产生第一个事件
            while (eventType != XmlPullParser.END_DOCUMENT) {
                // 只要不是文档结束事件
                switch (eventType) {
                    case XmlPullParser.START_TAG:
                        String name = parser.getName();// 获取解析器当前指向的元素的名称
                        if ("getJGOfficeResult".equals(name)) {
                            return parser.nextText();
                        }
                        break;
                }
                eventType = parser.next();
            }
            return null;
        } catch (XmlPullParserException | IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 生成替换后的xml字串
     */
    public static String createParam(Context context) {
        try {
            InputStreamReader inputReader = new InputStreamReader(context.getResources().getAssets().open("getJGOffice.xml"));
            BufferedReader bufReader = new BufferedReader(inputReader);
            String line;
            String Result = "";
            while ((line = bufReader.readLine()) != null)
                Result += line;
            Map<String, String> params = new HashMap<>();
            return CommonUtil.replace(Result, params);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
